export const createData = function (reducer, initData) {
  let deps = [];
  let data = initData;
  function subscribe(handler) {
    deps.push(handler);
  }
  function changeData(val) {
    data = val;
    deps.forEach((handler) => handler());
  }
  function getData() {
    return data;
  }
  function changeDataByAction(action) {
    data = reducer(data, action);
    deps.forEach((handler) => handler());
  }
  return {
    subscribe,
    changeData,
    getData,
    changeDataByAction,
  };
};

const initData = {
  count: 1,
};
const reducer = (data, action) => {
  switch (action.type) {
    case "add":
      return { ...data, count: data.count + 1 };
    case "change":
      return { ...data, count: action.payload };
    default:
      return data;
  }
};
export const dataObj = createData(reducer, initData);
